package com.threegroup.admin.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.threegroup.admin.service.ICaptchaService;
import com.threegroup.common.redis.RedisKeys;
import com.threegroup.common.redis.RedisUtils;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码
 */
@Service
public class CaptchaServiceImpl implements ICaptchaService {

    @Resource
    private RedisUtils redisUtils;

    @Value("${takeout.redis.open}")
    private boolean open;

    // 本地验证码存活 5 分钟
    Cache<String, String> localCache = CacheBuilder.newBuilder()
            .maximumSize(1000).expireAfterAccess(5, TimeUnit.MINUTES).build();

    /**
     * 验证码
     * @param response
     * @param uuid
     */
    @Override
    public void create(HttpServletResponse response, String uuid) throws IOException {

        // 设置响应头
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 生成验证码
        SpecCaptcha captcha = new SpecCaptcha(150, 40);
        captcha.setLen(5);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        captcha.out(response.getOutputStream());

        // 保存到缓存
        setCache(uuid, captcha.text());
    }

    @Override
    public boolean validate(String uuid, String code) {
        // 获取验证码
        String captcha = getCache(uuid);

        // 校验成功
        return code.equalsIgnoreCase(captcha);
    }

    /**
     * 设置验证码
     * @param uuid 用户唯一标识
     * @param text 验证码信息
     */
    private void setCache(String uuid, String text) {
        // redis 缓存开启 将验证码存储到 redis 中
        if (open) {
            String key = RedisKeys.getCaptchaKey(uuid);
            redisUtils.set(key, text, 300);
            return;
        }

        // redis 缓存没开启，将验证码存储到本地缓存中
        localCache.put(uuid, text);
    }

    /**
     * 获取验证码
     * @param key 唯一标识
     * @return 验证码信息
     */
    private String getCache(String key) {

        if (open) {
            key = RedisKeys.getCaptchaKey(key);
            String captcha = (String) redisUtils.get(key);
            // 删除验证码
            if (captcha != null) {
                redisUtils.delete(key);
            }
            return captcha;
        }

        String captcha = localCache.getIfPresent(key);
        // 删除验证码
        if (captcha != null) {
            localCache.invalidate(key);
        }

        return captcha;
    }
}
